package com.etop.shiro;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.etop.pojo.Function;
import com.etop.service.FunctionService;
import com.etop.service.PermissionService;
import com.etop.service.RoleService;

/**
 * @ 类名:ChainDefinitionSectionMetaSource
 * @ 描述:产生责任链，确定每个url的责任权限
 * @author Administrator
 * @ 日期:2016年11月17日
 */
public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section>{
    
	@Autowired
	private FunctionService functionService;
	@Resource
	private RoleService roleService;
	@Resource
	private PermissionService permissionService;
	//静态资源访问权限
	private String filterChainDefinitions="/static/**=anon";
	public Section getObject() throws Exception {
		// TODO Auto-generated method stub
		List<Function> list=functionService.findAll();
		Ini ini=new Ini();
		//加载默认的url
		ini.load(filterChainDefinitions);
		Ini.Section section=ini.getSection(ini.DEFAULT_SECTION_NAME);
		//循环resource的url，逐个添加到section中。section就是filterChainDefinitionMap,
		//里面的键就是url，值就是存在什么条件才能访问url
		for(Iterator<Function> it=list.iterator();it.hasNext();){
			Function function=it.next();
			int permission_id=function.getPermission_id();
			int role_id=function.getRole_id();
			//构成permission字符串
			if(StringUtils.isNotEmpty(function.getValue())
			        &&StringUtils.isNotEmpty(function.getType())){
				String permission="";
				if("anon".equals(function.getType())){
					permission="anon";
				}else if("perms".equals(function.getType())){
					permission="perms["+
					           permissionService.getNameById(permission_id)+"]";
				}else if("roles".equals(function.getType())){
					permission="roles["+
					           roleService.getNameById(role_id)+"]";
				}
				section.put(function.getValue(), permission);	
			}
		}
		//所有资源的访问权限必须放在最后
		section.put("/**", "authc");
		return section;
	}

	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return this.getClass();
	}
	

	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

}
